package org.amos.feign.interceptor;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.amos.core.basic.constant.SystemConstant;
import org.amos.core.basic.context.TenantContextHolder;
import org.slf4j.MDC;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;

public class CustomFeignRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //传递tenantId
        Long tenantId = TenantContextHolder.getTenantId();
        if (Objects.nonNull(tenantId)) {
            requestTemplate.header(SystemConstant.SYS_TENANT_NO, String.valueOf(tenantId));
        }
        //传递日志traceId
        String traceId = MDC.get(SystemConstant.TRACE_ID);
        if (StrUtil.isNotBlank(traceId)) {
            requestTemplate.header(SystemConstant.TRACE_ID, traceId);
        }
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (Objects.nonNull(attributes)) {
            //传递token
            String token = attributes.getRequest().getHeader(SystemConstant.SYS_TOKEN_KEY);
            if (StrUtil.isNotBlank(token)) {
                requestTemplate.header(SystemConstant.SYS_TOKEN_KEY, token);
            }
            //传递service-token 简单feign调用鉴权
            String serviceToken = attributes.getRequest().getHeader(SystemConstant.SYS_SERVICE_TOKEN_KEY);
            if (StrUtil.isNotBlank(serviceToken)) {
                requestTemplate.header(SystemConstant.SYS_SERVICE_TOKEN_KEY, serviceToken);
            }else {
                requestTemplate.header(SystemConstant.SYS_SERVICE_TOKEN_KEY, UUID.fastUUID().toString(true));
            }
        }
    }
}
